package app.adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.Checkable;
import android.widget.ImageView;
import android.widget.TextView;
import app.widget.MatchTextView;
import app.widget.PAPopupWindow;

import com.longevityassistant.activity.R;

/**
 * 带有表头表尾的Listview适配器
 * 
 * @author EX-ZHENGDUANCHUAN001
 * 
 */
public class TableAdapter extends BaseAdapter implements OnScrollListener {

	/**
	 * 第二列变色标志
	 */
	private String mFlag;
	/**
	 * mWindowManager
	 */
	private WindowManager mWindowManager;
	/**
	 * mWindowParams
	 */
	private WindowManager.LayoutParams mWindowParams;
	/**
	 * mContext
	 */
	private Context mContext;
	/**
	 * mDragView
	 */
	private TextView mDragView;

	/**
	 * mTo
	 */
	private int[] mTo;
	/**
	 * mFrom
	 */
	private String[] mFrom;
	/**
	 * mHeaderTo
	 */
	private int[] mHeaderTo;
	/**
	 * mFooterTo
	 */
	private int[] mFooterTo;

	/**
	 * mData
	 */
	private List<? extends Map<String, ?>> mData;
	/**
	 * mHeaderData
	 */
	private String[] mHeaderData;
	/**
	 * mFooterData
	 */
	private String[] mFooterData;

	/**
	 * mResource
	 */
	private int mResource;
	/**
	 * mHeaderResource
	 */
	private int mHeaderResource;
	/**
	 * mFooterResource
	 */
	private int mFooterResource;
	/**
	 * mInflater
	 */
	private LayoutInflater mInflater;
	/**
	 * listener
	 */
	private OnDetailViewClickListener listener;
	/**
	 * rightButtonListener
	 */
	private OnRightButtonClickListener rightButtonListener;
	/**
	 * 保存右边按钮
	 */
	private List<TextView> mRightButtonList;
	/**
	 * 右边按钮显示文字
	 */
	private String mRightButtonText;
	/**
	 * 是否开启右边按钮
	 */
	private boolean mIsOpen;
	/**
	 * 是否显示右边按钮
	 */
	private boolean mIsShow;

	/**
	 * mDensity
	 */
	private float mDensity;

	/**
	 * TableListView适配器
	 * 
	 * @param context
	 *            上下文
	 * @param headerResource
	 *            表头布局资源
	 * @param headerDate
	 *            表头数据
	 * @param headerTo
	 *            用来映射数据与布局的控件ID
	 * @param footerResource
	 *            表尾布局资源
	 * @param footerDate
	 *            表尾数据
	 * @param footerTo
	 *            用来映射数据与布局的控件ID
	 * @param resource
	 *            项LIST布局资源
	 * @param data
	 *            项数据
	 * @param from
	 *            项数据MAP中对应的键
	 * @param to
	 *            映射list数据与布局文件的控件ID
	 * @param flag
	 *            数据中的MAP键，识别是否更改字颜色
	 */
	public TableAdapter(Context context, int headerResource, String[] headerDate, int[] headerTo,
			int footerResource, String[] footerDate, int[] footerTo, int resource,
			List<? extends Map<String, ?>> data, String[] from, int[] to, String flag) {
		mHeaderResource = headerResource;
		mHeaderData = headerDate;
		mHeaderTo = headerTo;
		mFooterResource = footerResource;
		mFooterData = footerDate;
		mFooterTo = footerTo;
		mResource = resource;
		mData = data;
		if (mData == null) {
			mData = new ArrayList<Map<String, Object>>();
		}
		mFrom = from;
		if (mFrom == null) {
			mFrom = new String[0];
		}
		mTo = to;
		if (mTo == null) {
			mTo = new int[0];
		}
		mFlag = flag;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics displayMetrics = new DisplayMetrics();
		mWindowManager.getDefaultDisplay().getMetrics(displayMetrics);
		mDensity = displayMetrics.density;
		mContext = context;
		mRightButtonList = new ArrayList<TextView>();
	}

	/**
	 * 设置主体数据
	 * 
	 * @param data
	 *            数据
	 */
	public void setData(List<? extends Map<String, ?>> data) {
		if (data == null) {
			data = new ArrayList<Map<String, Object>>();
		}
		mData = data;
	}

	/**
	 * 添加项数据
	 * 
	 * @param data
	 *            数据
	 */
	public void addData(List<Map<String, Object>> data) {
		if (data != null) {
			((List<Map<String, Object>>) mData).addAll(data);
		}
	}

	/**
	 * 获取项数量
	 * 
	 * @return size
	 */
	public int getCount() {
		return mData.size();
	}

	/**
	 * 根据位置获取项
	 * 
	 * @param position
	 *            position
	 * @return item
	 */
	public Object getItem(int position) {
		return mData.get(position);
	}

	/**
	 * 获取项ID
	 * 
	 * @param position
	 *            position
	 * @return id
	 */
	public long getItemId(int position) {
		return position;
	}

	/**
	 * 获取项view
	 * 
	 * @param position
	 *            position
	 * @param convertView
	 *            convertView
	 * @param parent
	 *            parent
	 * @return view
	 */
	public View getView(int position, View convertView, ViewGroup parent) {
		return createViewFromResource(position, convertView, parent, mResource);
	}
	
	/**
	 * 获取简单的项view，用来计算高度
	 * 
	 * @param position
	 *            position
	 * @return view
	 */
	public View getCleanView(int position) {
		View v = mInflater.inflate(mResource, null);
		Map<String, ?> dataSet = mData.get(position);
		String[] from = mFrom;
		int[] to = mTo;
		int toCount = to.length;
		int fromCount = from.length;

		for (int i = 0; i < toCount && i < fromCount; i++) {
			Object data = dataSet.get(from[i]);
			String text = data == null ? "" : data.toString();
			if (text.equals("null")) {
				text = "";
			}
			setViewText((TextView) v.findViewById(to[i]), text);
		}
		return v;
	}

	/**
	 * 创建主体LISTVIEW
	 * 
	 * @param position
	 *            position
	 * @param convertView
	 *            convertView
	 * @param parent
	 *            parent
	 * @param resource
	 *            resource
	 * @return view
	 */
	private View createViewFromResource(int position, View convertView, ViewGroup parent,
			int resource) {
		View v;
		// 优化处理
		if (convertView == null) {
			v = mInflater.inflate(resource, parent, false);

			final int[] to = mTo;
			final int count = to.length;
			final List<View> holder = new ArrayList<View>();

			for (int i = 0; i < count; i++) {
				holder.add(v.findViewById(to[i]));
			}
			// 判断是否开启右边按钮 默认不开启
//			if (mIsOpen) {
//				final TextView rightButton = (TextView) v.findViewById(R.id.rightButton);
//				if (rightButton == null) {
//					mIsOpen = false;
//				} else {
//					mRightButtonList.add(rightButton);
//					holder.add(rightButton);
//
//					if (mRightButtonText != null) {
//						mIsShow = true;
//						rightButton.setText(mRightButtonText);
//						rightButton.setVisibility(TextView.VISIBLE);
//					}
//				}
//			}

			v.setTag(holder);
		} else {
			v = convertView;
		}

		bindView(position, v);

		v.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
//				stopDragging();
				PAPopupWindow.getInstance().dismissPopupWindow();
				return false;
			}
		});
		return v;
	}

	/**
	 * 绑定数据到布局中的对应控件
	 * 
	 * @param position
	 *            position
	 * @param view
	 *            view
	 */
	private void bindView(final int position, View view) {
		final Map<String, ?> dataSet = mData.get(position);
		if (dataSet == null) {
			return;
		}

		final List<View> holder = (List<View>) view.getTag();
		final String[] from = mFrom;
		final int[] to = mTo;
		final int toCount = to.length;
		final int fromCount = from.length;

		final StringBuilder detail = new StringBuilder();
		for (int i = 0; i < toCount && i < fromCount; i++) {
			final View v = holder.get(i);
			if (v != null) {
				final Object data = dataSet.get(from[i]);
				String text = data == null ? "" : data.toString();
				if (text.equals("null")) {
					text = "";
				}
				detail.append("   ").append(text);
				if (v instanceof Checkable) {
					if (data instanceof Boolean) {
						((Checkable) v).setChecked((Boolean) data);
					} else {
						throw new IllegalStateException(v.getClass().getName()
								+ " should be bound to a Boolean, not a " + data.getClass());
					}
				} else if (v instanceof TextView) {
					setViewText((TextView) v, text);
				} else if (v instanceof ImageView) {
					if (data instanceof Integer) {
						setViewImage((ImageView) v, (Integer) data);
					} else {
						setViewImage((ImageView) v, text);
					}
				} else {
					throw new IllegalStateException(v.getClass().getName() + " is not a "
							+ " view that can be bounds by this SimpleAdapter");
				}
			}
		}

		// 第一列单击事件，显示完整的信息
		View v = holder.get(0);

		if (listener != null) {
			v.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (listener != null) {
						listener.onDetailViewClick(v, position, detail.toString().trim());
					}
				}
			});
		}

		// 判断是否开启右边按钮 开启则设置单击事件
		if (mIsOpen) {
			final View rightButton = holder.get(holder.size() - 1);
			rightButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (rightButtonListener != null) {
						rightButtonListener.onRightButtonClick(rightButton, position,
								TableAdapter.this);
					}
				}
			});
		}

		// 根据标志更改颜色
		if (mFlag != null) {
			String flagV = (String) dataSet.get(mFlag);
			if (flagV.equals("0")) {
				((TextView) holder.get(1)).setTextColor(v.getResources().getColor(
						R.color.colorSelection));
			} else {
				((TextView) holder.get(1)).setTextColor(v.getResources().getColor(
						R.color.solid_green));
			}
		}
	}

	/**
	 * 获取第一列单击监听对象
	 * 
	 * @return listener
	 */
	public OnDetailViewClickListener getOnDetailViewClickListener() {
		return listener;
	}

	/**
	 * 设置第一列单击监听对象
	 * 
	 * @param l
	 *            l
	 */
	public void setOnDetailViewClickListener(OnDetailViewClickListener l) {
		listener = l;
	}

	/**
	 * 获取右边view单击监听对象
	 * 
	 * @return listener
	 */
	public OnRightButtonClickListener getOnRightButtonClickListener() {
		return rightButtonListener;
	}

	/**
	 * 设置右边view单击监听对象
	 * 
	 * @param l
	 *            l
	 */
	public void setOnRightButtonClickListener(OnRightButtonClickListener l) {
		rightButtonListener = l;
	}

	/**
	 * 第一列单击事件处理
	 * 
	 */
	private void setDetailViewOnClickListene() {
		PAPopupWindow.getInstance().init(mContext);
		listener = new OnDetailViewClickListener() {

			@Override
			public void onDetailViewClick(View v, int position, String detail) {
				Object object = PAPopupWindow.getInstance().getTag();
				if (object != null && ((Integer) object) == position) {
					return;
				}
				int width = (int)(305f * mDensity);
				int x = (int)(8f * mDensity);
				int y = (int)(-40f * mDensity);
				PAPopupWindow.getInstance().showPopupWindow(
						v, detail, width, LayoutParams.WRAP_CONTENT, x, y);
				PAPopupWindow.getInstance().setTag(position);
//				if (mDragView != null) {
//					if (((Integer) mDragView.getTag()) == position) {
//						return;
//					} else {
//						stopDragging();
//					}
//				}
//				int[] location = new int[2];
//				v.getLocationOnScreen(location);
//				DisplayMetrics displayMetrics = new DisplayMetrics();
//				mWindowManager.getDefaultDisplay().getMetrics(displayMetrics);
//				float density = displayMetrics.density;
//				mWindowParams = new WindowManager.LayoutParams();
//				mWindowParams.gravity = Gravity.TOP | Gravity.LEFT;
//				mWindowParams.x = (int) (8f * density);
//				mWindowParams.y = location[1] - (int) (40f * density);
//
//				mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
//				mWindowParams.width = (int) (305f * density);
//
//				mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//						| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
//						| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
//				mWindowParams.format = PixelFormat.TRANSLUCENT;
//				mWindowParams.windowAnimations = 0;
//
//				TextView tv = (TextView) mInflater.inflate(R.layout.detail_view, null, false);
//				tv.setTag(position);
//				tv.setText(detail);
//				tv.setOnClickListener(new OnClickListener() {
//
//					@Override
//					public void onClick(View v) {
//						stopDragging();
//					}
//				});
//
//				mWindowManager.addView(tv, mWindowParams);
//				mDragView = tv;
//				mWindowManager.updateViewLayout(mDragView, mWindowParams);
			}
		};
	}

	/**
	 * 获取表头
	 * 
	 * @return View
	 */
	public View getHeaderView() {
		if (mHeaderResource == 0) {
			return null;
		}
		View layout = mInflater.inflate(mHeaderResource, null, false);
		if (mHeaderData == null || mHeaderData.length == 0) {
			return layout;
		}

		final String[] data = mHeaderData;
		final int[] to = mHeaderTo;
		final int count = to.length;

		for (int i = 0; i < count; i++) {
			View v = layout.findViewById(to[i]);
			String text = data[i];
			if (text == null) {
				text = "";
			}

			if (v instanceof TextView) {
				setViewText((TextView) v, text);
			} else {
				throw new IllegalStateException(v.getClass().getName() + " is not a "
						+ " view that can be bounds by this Adapter");
			}
		}
		return layout;
	}

	/**
	 * 获取表尾
	 * 
	 * @return View
	 */
	public View getFooterView() {

		if (mFooterData == null || mFooterData.length == 0) {
			return null;
		}
		View layout = mInflater.inflate(mFooterResource, null, false);

		final String[] data = mFooterData;
		final int[] to = mFooterTo;
		final int count = to.length;

		for (int i = 0; i < count; i++) {
			View v = layout.findViewById(to[i]);
			String text = data[i];
			if (text == null) {
				text = "";
			}

			if (v instanceof TextView) {
				setViewText((TextView) v, text);
			} else {
				throw new IllegalStateException(v.getClass().getName() + " is not a "
						+ " view that can be bounds by this Adapter");
			}
		}
		return layout;
	}

	/**
	 * 设置ImageView
	 * 
	 * @param v
	 *            ImageView
	 * @param value
	 *            value
	 */
	private void setViewImage(ImageView v, int value) {
		v.setImageResource(value);
	}

	/**
	 * 设置ImageView
	 * 
	 * @param v
	 *            ImageView
	 * @param value
	 *            value
	 */
	private void setViewImage(ImageView v, String value) {
		try {
			v.setImageResource(Integer.parseInt(value));
		} catch (NumberFormatException nfe) {
			v.setImageURI(Uri.parse(value));
		}
	}

	/**
	 * setViewText
	 * 
	 * @param v
	 *            TextView
	 * @param text
	 *            text
	 */
	private void setViewText(TextView v, String text) {
		//使用MatchTextView规避混淆代码时找不到类
		if (v instanceof MatchTextView ) {
			((MatchTextView)v).setText(text);
		}
		v.setText(text);
	}

	/**
	 * 销毁信息提示窗口
	 */
	public void stopDragging() {
		PAPopupWindow.getInstance().dismissPopupWindow();
//		if (mDragView != null) {
//			mWindowManager.removeView(mDragView);
//			mDragView = null;
//		}
	}

	/**
	 * 是否显示右边按钮
	 * 
	 * @param isShow
	 *            是否显示
	 */
	public void showRightButton(boolean isShow) {
		if (mIsOpen == false || mIsShow == isShow) {
			return;
		}
		mIsShow = isShow;
		if (isShow) {
			setRightButtonVisibility(TextView.VISIBLE);
		} else {
			setRightButtonVisibility(TextView.INVISIBLE);
		}
	}
	
	/**
	 * 是否详细PopupWindow
	 * 
	 * @param isShow
	 *            是否显示
	 */
	public void showDetailView(boolean isShow) {
		if (isShow) {
			setDetailViewOnClickListene();
		} else {
			setOnDetailViewClickListener(null);
		}
	}

	/**
	 * 开启右边按钮并决定是否显示右边按钮
	 * 
	 * @param isOpen
	 *            是否开启
	 * @param text
	 *            显示按钮并设置显示文字
	 */
	public void openRightButton(boolean isOpen, String text) {
		mIsOpen = isOpen;
		mRightButtonText = text;
	}

	/**
	 * 设置右边按钮显示文字
	 * 
	 * @param text
	 *            设置显示文字
	 */
	public void setRightButtonText(String text) {
		if (text == null) {
			text = "";
		}
		mRightButtonText = text;
		for (TextView button : mRightButtonList) {
			button.setText(text);
		}
	}

	/**
	 * 显示右边按钮
	 * 
	 * @param visibility
	 *            是否可见
	 */
	private void setRightButtonVisibility(int visibility) {
		for (TextView button : mRightButtonList) {
			button.setVisibility(visibility);
		}
	}

	public interface OnDetailViewClickListener {
		/**
		 * 项左边TextView单击事件
		 * 
		 * @param view
		 *            触发事件的View
		 * @param position
		 *            项位置
		 * @param detail
		 *            项信息
		 */
		public void onDetailViewClick(View view, int position, String detail);
	}

	public interface OnRightButtonClickListener {
		/**
		 * 项右边按钮单击事件
		 * 
		 * @param view
		 *            触发事件的view
		 * @param position
		 *            项位置
		 * @param adapter
		 *            数据源
		 */
		public void onRightButtonClick(View view, int position, Adapter adapter);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
			int totalItemCount) {
		PAPopupWindow.getInstance().dismissPopupWindow();
//		stopDragging();
	}
	
	/**
	 * 详细PopupWindow是否处于显示状态
	 * @return 显示状态
	 */
	public boolean detailViewIsShowing() {
		return mDragView == null ? false : true;
	}
}
